package guoanmaker.operator.business.service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import guoanmaker.operator.business.model.Patent;
import guoanmaker.operator.business.model.PatentQueryRecord;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.TestToken;
import guoanmaker.operator.business.modelnobind.LikePatentModel;
import guoanmaker.operator.business.modelnobind.PatentRo;
import guoanmaker.operator.business.repository.PatentRepository;
import guoanmaker.operator.business.repository.PatentQueryRecordRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.TestTokenRepository;
import guoanmaker.operator.helper.common.util.HttpGetUtil;

@Service
public class PatentSearchService {
	// 版本号，当前版本号为1
	private static final int version = 1;
	// 用户身份识别的重要依据
//	private static int i = 0;
//	private static final String[] token = {"d4e221f9a112a543d301b3595bc25c108dcffc05","1ee1aa5c1406de0b33d3e0d16d468ea90ed033a5","0a443a0deac2e12fb72b142747059772af129257","04cd58ceaf87012ac69a2b094a98f520541c4cd5","e9a8fcf692829dbdb9fb17ef8dd6852c3f5d5c7a","4661aece85c1df2d856fa0010a0b00e945c60225","4661aece85c1df2d856fa0010a0b00e945c60225","feed193f203d8d3ffebb5c0aa09d766bce238672","feed193f203d8d3ffebb5c0aa09d766bce238672"};
	
	@Resource
	private OperatorResidueCountService residueCountService;
	@Autowired
	private PatentQueryRecordRepository patentQueryRecordRepository;
	@Autowired
	private PersonalUserRepository personalUserRepository;
	@Autowired
	private PatentRepository patentRepository;
	@Autowired
	private TestTokenRepository tokenRepository;
	/**
	 * 
	 * @Title: getPatentsByKeyWord
	 * @Description: 查询指定关键字的专利信息
	 * @param keyWord
	 *            用户输入的查询条件
	 * @param page
	 *            页码，默认值1，最大页码为100页
	 * @param pageSize
	 *            每页展现数据的条数，默认10条，单页最大50条
	 * @return Object
	 * @throws UnsupportedEncodingException
	 */
	public Object getPatentsByKeyWord(String userid,String keyWord, int page, int pageSize) throws UnsupportedEncodingException {
		
		if(page >= 3) {
			return "没有更多的结果了";
		}
		
		int detailNumber = Integer.parseInt(residueCountService.patentSearchDetail().get("count").toString());
		if(detailNumber <= 0) {
			return "查询次数用尽，请明天再试";
		}
		
		residueCountService.patentSearchMinusOne();
		
		List<TestToken> tokens = tokenRepository.findBySearchCountGreaterThan(0);
		if(tokens.size() == 0) {
			return "查询次数用尽，请明天再试";
		}
		
		TestToken testToken = tokens.get(0);
		testToken.setSearchCount(testToken.getSearchCount() - 1);
		String token = testToken.getToken();
		tokenRepository.save(testToken);
		
		PersonalUser personalUser = personalUserRepository.getOne(userid);
		PatentQueryRecord queryRecord = new PatentQueryRecord();
		queryRecord.setKeyWrod(keyWord);
		queryRecord.setQueryDate(new Date());
		queryRecord.setUser(personalUser);
		
		patentQueryRecordRepository.save(queryRecord);
		
		String baseUrl = "https://www.patenthub.cn/api/s?";
		StringBuffer url = new StringBuffer();
		url.append(baseUrl).append("&t=").append(token).append("&q=").append(keyWord).append("&p=").append(page)
				.append("&ps=").append(pageSize).append("&v=").append(version);
		String patents = HttpGetUtil.httpBigGet(url.toString());
		JSONObject parseObject = JSON.parseObject(patents);
		LikePatentModel models = JSON.toJavaObject(parseObject, LikePatentModel.class);
		models.setQueryCount(detailNumber);
		int queryInfoCount = Integer.parseInt(residueCountService.patentSearchInfoDetail().get("count").toString());
		models.setQueryInfoCount(queryInfoCount);
		return models.isSuccess() ? models : "查询次数用尽，请明天再试";
	}

	/**
	 * 
	 * @Title: getPatentById
	 * @Description: 根据ID查询指定专利信息
	 * @param id 专利ID
	 * @returnObject
	 * @throws UnsupportedEncodingException
	 */
	public Object getPatentById(String userid,String id,String keyWord) throws UnsupportedEncodingException {
		
		Patent repeatPatent = patentRepository.findOne(id);
		if(repeatPatent != null && !"".equals(repeatPatent.getTitle())) {
			return repeatPatent;
		}
		
		if(Integer.parseInt(residueCountService.patentSearchInfoDetail().get("count").toString()) <= 0) {
			return "查询次数用尽，请明天再试";
		}
		
		List<TestToken> tokens = tokenRepository.findBySearchInfoCountGreaterThan(0);
		if(tokens.size() == 0) {
			return "查询次数用尽，请明天再试";
		}
		
		TestToken testToken = tokens.get(0);
		testToken.setSearchInfoCount(testToken.getSearchInfoCount() - 1);
		String token = testToken.getToken();
		tokenRepository.save(testToken);
		
		residueCountService.patentInfoSearchMinusOne();
		String baseUrl = "https://www.patenthub.cn/api/patent/base?";
		StringBuffer url = new StringBuffer();
		url.append(baseUrl).append("&t=").append(token).append("&id=").append(id).append("&v=").append(version);
		String patent = HttpGetUtil.httpBigGet(url.toString());
		JSONObject parseObject = JSON.parseObject(patent);
		PersonalUser personalUser = personalUserRepository.getOne(userid);
		PatentRo currentPatent = JSON.toJavaObject(parseObject.getJSONObject("patent"), PatentRo.class);
		//缓存 patent
		Patent savedPatent = new Patent(userid, currentPatent);
		patentRepository.save(savedPatent);		
		
		List<PatentQueryRecord> queryRecords = patentQueryRecordRepository.findByUserIdAndKeyWrod(keyWord, userid);
		if(queryRecords.size() > 0) {
			PatentQueryRecord queryRecord = queryRecords.get(0);
			for (PatentQueryRecord patentQueryRecord : queryRecords) {
				if(queryRecord.getQueryDate().before(patentQueryRecord.getQueryDate())){
					queryRecord = patentQueryRecord;
				}
			}
			queryRecord.setUser(personalUser);
			queryRecord.setQueryDate(new Date());
			if(queryRecord.getKind() == null && queryRecord.getTitle() == null){
				queryRecord.setKind(currentPatent.getType());
				queryRecord.setTitle(currentPatent.getTitle());
			}else {
				queryRecord.setKind(queryRecord.getKind() + ";" + currentPatent.getType());
				queryRecord.setTitle(queryRecord.getTitle() + ";" +currentPatent.getTitle());
			}
			patentQueryRecordRepository.save(queryRecord);
		}
		
		return parseObject.get("success").toString().equals("true")
				? currentPatent : "查询次数用尽，请明天再试";
	}
	/**
	 * 
	 * @Title: cleanCache
	 * @Description: 清空用户查询缓存
	 * @param userid 用户id
	 * @return int 
	 * @throws
	 */
	public int cleanCache(String userid){
		return patentRepository.deletePatentByUserid(userid);
	}
	
}
